/**
 * @param {string} s
 * @return {number}
 */
 var calculate = function(s) {
    let num = [],symbol = [],q = [];
    const em = {
        '+':2,
        '-':2,
        '*':3,
        '/':3,
        '(':1,
        ')':1
    };
    s = s.replace(/ /g,'');
    for(let i = 0; i < s.length; i++){
        let n = '';
        if(!em[s[i]]){
            while(!em[s[i]] && i < s.length) n += s[i++];
            num.push(n);
        }
        if(i >= s.length) break;
        if(s[i] == '-' && (i == 0 || (em[s[i - 1]] && s[i - 1] != ')'))){
            num.push(0);
        }
        num.push(s[i]);
    }
    const calc = function(b,a,symbol){
        b = parseInt(b);
        a = parseInt(a);
        switch(symbol){
            case '+':
                return a + b;
            case '-':
                return a - b;
            case '*':
                return a * b;
            case '/':
                return a / b;
        }
    };
    num.map(item=>{
        if(em[item]){
            if(item == ')'){
                while(symbol.length && symbol[symbol.length - 1] != '('){
                    q.push(calc(q.pop(),q.pop(),symbol.pop()));
                }
                symbol.pop();
            }else if(item != '('){
                while(symbol.length && em[symbol[symbol.length - 1]] >= em[item]){
                    let sy = symbol.pop();
                    if(!['(',')'].includes(sy)){
                        q.push(calc(q.pop(),q.pop(),sy));
                    }
                }
            }
            if(item != ')') symbol.push(item);
        }else{
            q.push(item);
        }
    });
    while(symbol.length) q.push(calc(q.pop(),q.pop(),symbol.pop()));
    return parseInt(q[0]);
};